package com.monkeygroup.mygoplus.ecchat.ui.contact;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.ecchat.common.utils.ToastUtil;
import com.monkeygroup.mygoplus.ecchat.ui.chatting.IMChattingHelper;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.MemberListAdapter;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.monkeygroup.mygoplus.ecchat.ui.group.CreateNewGroup;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by Administrator on 2017/5/21.
 */
public class AddFriendMainActivity extends BaseActivity implements View.OnClickListener, PlatformActionListener {
    private ListView new_friends_listview;
    private List<ContactMemberDTO> resultList = new ArrayList<>();
    private MemberListAdapter adapter;
    private Dialog dialog = null;
    private final int REQUEST_SHARE_FRIEND = 121;
    private final String shareMsg = "http://www.mygo.com/ \n" + "MyGo房產物件APP，一起來下載吧！";
    private final String TAG = "AddFriendMain";

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_addfriend_main);
    }

    @Override
    public void initView() {
        new_friends_listview = (ListView) findViewById(R.id.new_friends_listview);
    }

    @Override
    public void setListener() {
        findViewById(R.id.layout_back).setOnClickListener(this);
        findViewById(R.id.layout_friend_invite).setOnClickListener(this);
        findViewById(R.id.layout_friend_radar).setOnClickListener(this);
        findViewById(R.id.layout_friend_scan).setOnClickListener(this);
        findViewById(R.id.layout_friend_shake).setOnClickListener(this);
        findViewById(R.id.layout_friend_search).setOnClickListener(this);
        findViewById(R.id.layout_create_group).setOnClickListener(this);
    }

    @Override
    public void doEvent() {
        initAdapter();

        doRecommendResult();
    }

    private void createDialog() {
        dialog = new Dialog(this, R.style.MyDialogTheme);
        dialog.show();

        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        lp.width = MyGoApplication.fullScreenWidth - 80;
        dialogWindow.setAttributes(lp);

        dialogWindow.setContentView(R.layout.dialog_invite_share);

        dialogWindow.findViewById(R.id.layout_mygo_share).setOnClickListener(this);
        dialogWindow.findViewById(R.id.layout_email_share).setOnClickListener(this);
        dialogWindow.findViewById(R.id.layout_facebook_share).setOnClickListener(this);
        dialogWindow.findViewById(R.id.layout_wechat_share).setOnClickListener(this);
        dialogWindow.findViewById(R.id.dialog_cancel).setOnClickListener(this);
    }

    private void initAdapter() {
        adapter = new MemberListAdapter(AddFriendMainActivity.this, resultList);
        new_friends_listview.setAdapter(adapter);
    }

    private void setResultData(List<Map<String, Object>> list) {
        resultList.clear();
        for (Map<String, Object> item : list) {
            ContactMemberDTO memberDTO = new ContactMemberDTO();
            if (item.get("username") != null && !item.get("username").equals("")) {
                memberDTO.setName((String) item.get("username"));
            } else if (item.get("userID") != null && !item.get("userID").equals("")) {
                memberDTO.setName((String) item.get("userID"));
            } else {
                memberDTO.setName((String) item.get("mobile"));
            }

            memberDTO.setId((String) item.get("mobile"));
            memberDTO.setHeadUrl((String) item.get("headIcon"));
            resultList.add(memberDTO);
        }

        adapter.notifyDataSetChanged();
    }

    /**
     * 獲取可能認識的人的列表
     **/
    private void doRecommendResult() {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestRaderList;
        HttpModel httpModel = new HttpModel(requestUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, Object> map = (Map) data;
                    List<Map<String, Object>> list = (ArrayList) map.get("list");
                    setResultData(list);
                } else {
                    ToastUtil.showMessage(resultMsg);
                }
            }
        }, true);

        httpModel.startRequest();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_friend_invite:
                createDialog();
                break;
            case R.id.layout_friend_radar:
                intent.setClass(this, LocatingSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_friend_scan:
                intent.setClass(this, ScanAddFriendActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_friend_shake:
                intent.setClass(this, ShakeSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_friend_search:
                intent.setClass(this, AddFriendSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_create_group:
                intent.setClass(this, CreateNewGroup.class);
                startActivity(intent);
                break;
            case R.id.layout_mygo_share:
                //這個地方應該是直接發送給好友固定的文本信息或者富文本信息
                intent.setClass(this, InviteContactActivity.class);
                startActivityForResult(intent, REQUEST_SHARE_FRIEND);
//                intent.setAction(Intent.ACTION_SEND);
//                intent.setType("text/plain");
//                intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "應用商店");
//                intent.putExtra(Intent.EXTRA_TEXT, "https://www.jd.com");
//                startActivity(Intent.createChooser(intent, "Share"));
                break;
            case R.id.layout_email_share:
                sendMail();
                break;
            case R.id.layout_facebook_share:
                share_fbFriend();
                break;
            case R.id.layout_wechat_share:
                share_WxFriend();
                break;
            case R.id.dialog_cancel:
                dialog.dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 发送邮件
     **/
    private void sendMail() {
        Uri uri = Uri.parse("mailto:3802**92@qq.com");
        String[] email = {"3802**92@qq.com"};
        Intent intent = new Intent(Intent.ACTION_SENDTO);
//        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
//        intent.putExtra(Intent.EXTRA_CC, email); // 抄送人
        intent.putExtra(Intent.EXTRA_SUBJECT, "歡迎使用MyGo房產物件APP");
        intent.putExtra(Intent.EXTRA_TEXT, "MyGo房產物件APP，一起來下載吧\n http://www.mygo.com/");
        startActivity(Intent.createChooser(intent, "請選擇使用郵件"));
    }

    /**
     * 分享到微信好友
     */
    private void share_WxFriend() {
        // 初始化sdk分享资源
        ShareSDK.initSDK(this);

        // 初始化要属相的内容
        String share_title = "MyGo房產APP";
        String share_text = "MyGo房產物件，一起來下載吧";
        String share_image = "http://www.mygo.com/mygo/images/logo.png";
        String share_url = "http://www.mygo.com/";

        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
        if (!platform.isValid()) {
            ToastUtil.showMessage("分享失敗，請先安裝wechat");
            return;
        }

        HashMap<String, Object> map = new HashMap<>();
//        map.put("AppId", ShareConfig.APPID_WXFRIEND);
//        map.put("Enable", ShareConfig.ENABLE_WXFRIEND);
//        map.put("BypassApproval", ShareConfig.BYPASSAPPROVAL_WXFRIEND);

        ShareSDK.setPlatformDevInfo(Wechat.NAME, map);
        ShareSDK.initSDK(this, "1c615185e4e7e");

        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);// 一定要设置分享属性
        sp.setTitle(share_title);
        sp.setText(share_text);
        sp.setImageData(null);
        sp.setImageUrl(share_image);
        sp.setImagePath("");
        sp.setUrl(share_url);

        platform.setPlatformActionListener(this); // 设置分享事件回调
        // 执行图文分享
        platform.share(sp);
    }

    private void share_fbFriend() {
        // 初始化sdk分享资源
        ShareSDK.initSDK(this);

        // 初始化要属相的内容
        String share_title = "MyGo房產APP";
        String share_text = "MyGo房產物件，一起來下載吧";
        String share_image = "http://www.mygo.com/mygo/images/logo.png";
        String share_url = "http://www.mygo.com/";

        Platform platform = ShareSDK.getPlatform(Facebook.NAME);
        if (!platform.isValid()) {
            ToastUtil.showMessage("分享失敗，請先安裝facebook");
            return;
        }

        HashMap<String, Object> map = new HashMap<>();
//        map.put("AppId", ShareConfig.APPID_WXFRIEND);
//        map.put("Enable", ShareConfig.ENABLE_WXFRIEND);
//        map.put("BypassApproval", ShareConfig.BYPASSAPPROVAL_WXFRIEND);

        ShareSDK.setPlatformDevInfo(Facebook.NAME, map);
        ShareSDK.initSDK(this, "1c615185e4e7e");

        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);// 一定要设置分享属性
        sp.setTitle(share_title);
        sp.setText(share_text);
        sp.setImageData(null);
        sp.setImageUrl(share_image);
        sp.setImagePath("");
        sp.setUrl(share_url);

        platform.setPlatformActionListener(this); // 设置分享事件回调
        // 执行图文分享
        platform.share(sp);
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }

    private void handleSendTextMessage(String receiver) {
        // 组建一个待发送的ECMessage
        ECMessage msg = ECMessage.createECMessage(ECMessage.Type.TXT);

        // 设置消息接收者
        msg.setTo(receiver);
        ECTextMessageBody msgBody = null;
        // 创建一个文本消息体，并添加到消息对象中
        msgBody = new ECTextMessageBody(shareMsg.toString());
        msg.setBody(msgBody);

        try {
            // 发送消息，该函数见上
            long rowId = -1;
            rowId = IMChattingHelper.sendECMessage(msg);
            // 通知列表刷新
            msg.setId(rowId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SHARE_FRIEND && resultCode == RESULT_OK) {
            List<String> friends = data.getStringArrayListExtra("list");
            for (String userid : friends) {
                handleSendTextMessage(userid);
            }
            ToastUtil.showMessage("分享消息已發出");
        }
    }
}
